
//自定义头文件
//#include "myhead.h"
//
//C的头文件
#include <signal.h>

//C++的头文件
#include <iostream>

using std::cout;
using std::endl;

//第三方库头文件
#include <workflow/WFFacilities.h>
#include <workflow/WFTaskFactory.h>
#include <workflow/HttpMessage.h>
#include <workflow/HttpUtil.h>

static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int num)
{
    printf("sig number %d is comming\n", num);
    waitGroup.done();
}

void httpCallback(WFHttpTask * httptask)
{
    //当回调函数被运行时，已经完成了数据的接收和发送了
    cout << "httpCallback is running" << endl;
    //1. 错误检测
    int state = httptask->get_state();
    int error = httptask->get_error();

    switch(state) {
    case WFT_STATE_SYS_ERROR:
        printf("system error: %s\n", strerror(error)); break;
    case WFT_STATE_DNS_ERROR:
        printf("dns error: %s\n", gai_strerror(error)); break;
    case WFT_STATE_SUCCESS:
        break;
    }

    if(state != WFT_STATE_SUCCESS) {
        printf("error occurs!\n");
        return;
    }

    printf("task success\n");

    //2.获取请求报文的信息
    //2.1起始行
    auto req = httptask->get_req();
    printf("%s %s %s\n", req->get_method(),
           req->get_request_uri(),
           req->get_http_version());

    //2.2首部字段,需要通过一个迭代器进行遍历
    protocol::HttpHeaderCursor cursor(req);
    std::string key, value;
    while(cursor.next(key, value)) {
        cout << key << ": " << value << endl;
    }
    cout << endl;

    //3. 获取响应报文的信息
    auto resp = httptask->get_resp();
    //3.1 起始行
    printf("%s %s %s\n",resp->get_http_version(),
           resp->get_status_code(),
           resp->get_reason_phrase());

    //3.2 首部字段
    protocol::HttpHeaderCursor cursor2(resp);
    while(cursor2.next(key, value)) {
        cout << key << ": " << value << endl;
    }

    //3.3 消息体
    const void * body = nullptr;
    size_t sz = 0;
    resp->get_parsed_body(&body, &sz);
    printf("%s\n", (const char *)body);

}

void test0()
{
    signal(SIGINT, sighandler);

    //1.创建了一个http任务
    WFHttpTask * httpTask = WFTaskFactory::create_http_task("http://localhost"
                                    ,1, 1, httpCallback);

    //2. 设置任务的属性
    auto req = httpTask->get_req();
    req->add_header_pair("User-Agent", "workflow http client");

    //3.将任务交给框架来执行,是由框架来调度
    httpTask->start();

    waitGroup.wait();
}


int main()
{
    test0();
    return 0;
}

